<script setup>
import {
  Clock,
  Delete,
  Edit,
  Search,
  RefreshRight,
  Plus,
} from '@element-plus/icons-vue'
import {ref,onMounted} from "vue";
import api from '@/utils/request.js';
import {formatDay, formatLoginTime} from '@/utils/date.js'
import {ElMessage, ElMessageBox} from "element-plus";
import loginUser from "@/stores/LoginUser.js";
let searchTime = ref(["",""])
let psearchTime = ref(["",""])
let queryParams =ref({})
let   userList = ref([])
let isSelectRow = ref(false)
let isAdd= ref(false);
const tableRef = ref(null);
const selectedRows = ref([]);
let resetQueryForm=()=>{
  queryParams.value = {
    pageNum:1,
    pageSize:10,
    activityName:'',
    type:'',
    approveStatus: '',
    start:'',
    end:'',
    pstart:'',
    pend:'',
    total:''
  };
  searchTime.value = ["", ""]; // 清空日期选择器
  psearchTime.value = ["", ""]; // 清空日期选择器
}
let query = ()=>{
  if (searchTime.value[0]!==''){
    queryParams.value.start = formatDay(searchTime.value[0])
    queryParams.value.end = formatDay(searchTime.value[1])
  }
  if (psearchTime.value[0]!==''){
    queryParams.value.pstart = formatDay(psearchTime.value[0])
    queryParams.value.pend = formatDay(psearchTime.value[1])
  }
  //后端来的数据

  api.get("/amActivity/page",queryParams.value).then(result=>{
    console.log(result.data.list)
    if (result.data && result.data.list) {
      userList.value = result.data.list;
      queryParams.value.total = result.data.total;
    } else {
      userList.value = [];
      queryParams.value.total = 0;
    }

  //  userList.value = result.data.list;
   // queryParams.value.total = result.data.total
    console.log(userList.value)  // 检查 userList.value 是否被正确更新
  })

}
// let switchHandler1 = (row)=>{
//   const name = row.activityName || row.id || '未知';
//   ElMessageBox.confirm(`是否修改活动[${name}]的状态？`, '提示', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning',
//   }).then(() => {
//     if (row.activityType === 0) {
//       row.activityType = 1;
//     } else {
//       row.activityType = 0;
//     }
//
//   }).catch(() => {
//     ElMessage.info('已取消修改');
//   })
// }

//
let switchHandler = (row) => {
  const name = row.activityName || row.id || '未知';
  ElMessageBox.confirm(`是否修改活动[${row.id}]的状态？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 实际状态变更
    row.activityType = row.activityType === 0 ? 1 : 0;

    // 发送请求更新状态
    api.post("/amActivity/save/update", row)
        .then(() => {
          ElMessage.success('状态更新成功');
        })
        .catch(() => {
          ElMessage.error('状态更新失败');
          row.activityType = row.activityType === 0 ? 1 : 0; // 回滚
        });
  }).catch(() => {
    ElMessage.info('已取消修改');
    row.activityType = row.activityType === 0 ? 1 : 0; // 回滚
  });
};



let editFormVisible = ref(false)
let editForm = ref({
  password : 123456,
  priceBeginTime: '', // 新增：价格开始时间
  priceEndTime: ''    // 新增：价格结束时间
})
let editTitle = ref('编辑')
let addPage = ()=>{
  editFormVisible.value = true
  isAdd.value = true
  editTitle.value = "新增用户"
  reset()
}
let editFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  nickname: [
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
  ]
}
let edit = (row)=>{
  console.log(row)
  editFormVisible.value = true
  isAdd.value = false
  editTitle.value = "编辑用户"
  editForm = ref(row)
  editForm.value.password = ''
  console.log(editForm.value.isvalid)
  editForm.value.approveStatus = String(editForm.value.approveStatus)
}
/** 取消按钮 */
function cancel() {
  editFormVisible.value = false;
  reset();
}
function reset(){
  editForm.value ={
    uid: '',
    username: '',
    nickname: '',
    phone: '',
    isvalid: '1',
    password: '123456',
    priceBeginTime: '', // 重置价格开始时间
    priceEndTime: ''    // 重置价格结束时间
  }
}
function save() {
  // 确保 approveStatus 是数字类型（后端可能需要）
  if (editForm.value.approveStatus === '0') {
    editForm.value.approveStatus = 0
  } else if (editForm.value.approveStatus === '1') {
    editForm.value.approveStatus = 1
  } else if (editForm.value.approveStatus === '2') {
    editForm.value.approveStatus = 2
  }

  //去掉editForm中的logintime属性
  console.log(editForm.value)
  delete editForm.value.loginTime;
  delete editForm.value.regTime;
  delete editForm.value.role;
  api.post("/amActivity/save/update",editForm.value).then(result=>{
    if (result.code === 200){
      ElMessage.success("添加/修改成功");
      query();
      cancel();
    }else {
      ElMessage.error(result.msg)
    }
  })
}

const handleSelectionChange = (val) => {
  selectedRows.value = val;
  isSelectRow.value = selectedRows.value.length > 0;
};
const deleteSelectedRows = () => {
  const idsArray = selectedRows.value.map(row => row.uid);

  ElMessageBox.confirm('是否确认删除用户编号为['+idsArray+']的数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    //ids变成,分割的字符串
    const ids = selectedRows.value.map(row => row.id).join(',');
    api.delete("/amActivity/del/"+ids).then(result=>{
      ElMessage.success("删除成功")
      query();
    })

  }).catch(() => {
    ElMessage.info('已取消删除');
  })

};
let deleteOne = (row)=>{
  ElMessageBox.confirm('是否确认删除用户编号为['+row.id+']的数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    api.delete("/amActivity/del/"+row.id).then(result=>{
      ElMessage.success("删除成功")
      query();
    })
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
 }
 let roleList = ref([])
 function queryRoleList(){
    api.post("/amActivity/save/update").then(result=>{//这里需要跟后端对接
      roleList.value = result.data;
    })

 }
// 数字转中文状态
const getApproveStatusText = (status) => {
  const map = {
    0: '未审核',
    1: '已审核',
    2: '审核不通过'
  };
  return map[status] || '未知';
};


function resetPassword (row) {
   const idsArray = selectedRows.value.map(row => row.uid);
  ElMessageBox.confirm('是否为ID为['+idsArray+']的用户重置密码为[123456]?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(({ value }) => {
    const ids = selectedRows.value.map(row => row.uid).join(',');

  })
 }

onMounted(()=>{
  resetQueryForm();
 // queryRoleList();
  query();
})




</script>

<template>
  <div class="app-container">
    <el-row>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="商品名称">
          <el-input v-model="queryParams.activityName"  clearable />
        </el-form-item>

<!--        <el-form-item label="审批状态" >-->
<!--          <el-select v-model="queryParams.id" placeholder="全部" maxlength="30">-->
<!--            <el-option-->
<!--                v-for="role in roleList"-->
<!--                :key="role.rid"-->
<!--                :label="role.name"-->
<!--                :value="role.rid"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="审批状态">
          <el-select
              v-model="queryParams.approveStatus"
              placeholder="全部"
              clearable
          >
            <el-option label="未审核" value="0" />
            <el-option label="已审核" value="1" />
            <el-option label="审核不通过" value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="活动状态">
          <el-select
              v-model="queryParams.type"
              placeholder="状态"
              clearable
          >
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动开始时间">
          <el-date-picker
              v-model="searchTime"
              type="daterange"
              unlink-panels
              range-separator="到"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              clearable
          />
        </el-form-item>
        <el-form-item label="价格生效时间">
          <el-date-picker
              v-model="psearchTime"
              type="daterange"
              unlink-panels
              range-separator="到"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              clearable
          />
        </el-form-item>
        <el-form-item >
          <el-button type="primary" :icon="Search" @click="query">查询</el-button>
          <el-button type="primary" :icon="RefreshRight" @click="resetQueryForm">重置</el-button>
        </el-form-item>
      </el-form>

    </el-row>
    <el-row>
      <el-col>

        <el-button  type="success" :icon="Plus" plain @click="addPage">新增</el-button>
        <el-button type="danger" :icon="Delete" plain @click="deleteSelectedRows" :disabled="!isSelectRow">删除</el-button>
        <el-button type="warning" :icon="Clock" plain @click="resetPassword" :disabled="!isSelectRow">重置密码</el-button>

      </el-col>
    </el-row>
    <el-row >
      <el-table
          :data="userList"
          border
          stripe
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
            prop="id"
            label="ID"
            width="80"
        />
        <el-table-column
            prop="activityName"
            label="活动名"
            width="80"
        />
        <el-table-column
            prop="activityBeginTime"
            label="活动开始时间"
            width="180"
        >
          <template #default="scope">
            {{ formatDay(scope.row.activityBeginTime) }}
          </template>
        </el-table-column>
        <el-table-column
            prop="activityEndTime"
            label="活动结束时间"
            width="180"
        >
          <template #default="scope">
            {{ formatDay(scope.row.activityEndTime) }}
          </template>
        </el-table-column>


        <el-table-column
            label="活动状态"
        >
          <template #default="scope">
            <!--status必须是String类型,否则switch组件不识别-->
            <el-switch
              :model-value="String(scope.row.activityType)"
                inline-prompt
                active-value="0"
                active-text="正常"
                inactive-value="1"
                inactive-text="停用"
                class="ml-2"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                @change="switchHandler(scope.row)"
            />

<!--            <el-switch-->
<!--                v-model="scope.row.activityType"-->
<!--                inline-prompt-->
<!--                active-value="0"-->
<!--                active-text="正常"-->
<!--                inactive-value="1"-->
<!--                inactive-text="停用"-->
<!--                class="ml-2"  style="&#45;&#45;el-switch-on-color: #13ce66; &#45;&#45;el-switch-off-color: #ff4949"-->
<!--            />-->


          </template>

        </el-table-column>
<!--        <el-table-column label="创建时间" >-->
<!--          <template #default="scope">-->
<!--            {{ formatDay(scope.row.regTime) }}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="最后登录时间" >-->
<!--          <template #default="scope">-->
<!--            {{ formatLoginTime(scope.row.loginTime) }}-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column prop="priceBeginTime" label="促销价格开始时间">
          <template #default="scope">
            {{ formatDay(scope.row.priceBeginTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="priceEndTime" label="促销价格结束时间">
          <template #default="scope">
            {{ formatDay(scope.row.priceEndTime) }}
          </template>
        </el-table-column>


        <el-table-column prop="approveStatus" label="审批状态">
          <template #default="scope">
            <el-tag
                :type="{
        '未审核': 'warning',
        '已审核': 'success',
        '审核不通过': 'danger'
      }[getApproveStatusText(scope.row.approveStatus)] || 'info'"
            >
              {{ getApproveStatusText(scope.row.approveStatus) }}
            </el-tag>
          </template>
        </el-table-column>


        <el-table-column prop="remark" label="备注" />

        <el-table-column label="操作" default="scope">
          <template #default="scope">
            <el-button type="primary" size="small" @click="edit(scope.row)">修改</el-button>
            <el-button type="danger" size="small" @click="deleteOne(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-col :span="24">

        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryParams.total"
            @size-change="query"
            @current-change="query"
        />
      </el-col>
    </el-row>
  </div>
  <!-- 添加用户信息 -->
  <el-dialog v-model="editFormVisible" :title="editTitle" width="600px" append-to-body>
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef"  label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="活动名" prop="activityName">
            <el-input v-model="editForm.activityName" placeholder="请输入活动名" maxlength="30" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="活动开始时间" prop="activityBeginTime">
            <el-date-picker
                v-model="editForm.activityBeginTime"
                type="date"
                placeholder="请选择开始时间"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                clearable
            />
          </el-form-item>
        </el-col>

      </el-row>


<!--      <el-row>-->
<!--        <el-col :span="12">-->
<!--          <el-form-item label="手机号" prop="phone">-->
<!--            <el-input v-model="editForm.phone" placeholder="手机号" maxlength="30" />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="12">-->
<!--          <el-form-item label="邮箱" prop="email">-->
<!--            <el-input v-model="editForm.email" placeholder="邮箱" maxlength="30" />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--      </el-row>   修改的时候会出现    -->
      <el-row>
<!--        <el-col :span="12" v-if="!isAdd">-->
<!--          <el-form-item label="昵称" prop="nickname">-->
<!--            <el-input v-model="editForm.nickname" placeholder="请输入用户昵称" maxlength="30" />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="12">
          <el-form-item label="状态" prop="activityType">
            <el-radio-group v-model="editForm.activityType" >
              <el-radio-button label="正常" :value="0" />
              <el-radio-button label="停用" :value="1" />
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
<!--        <el-col :span="12">-->
<!--          <el-form-item label="岗位" prop="phone">-->
<!--            <el-input  placeholder="岗位" maxlength="30" />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="12">
          <el-form-item label="审批状态" prop="approveStatus">
            <el-select v-model="editForm.approveStatus" placeholder="审核状态" maxlength="30">

              <el-option label="未审核" value="0" />
              <el-option label="已审核" value="1" />
              <el-option label="审核不通过" value="2" />

            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="editForm.remark" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>


</style>